/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef NODE_UTIL_LOCKED_QUEUE_H_
#define NODE_UTIL_LOCKED_QUEUE_H_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <deque>
#include "node/system/lock_guard.h"

namespace node {
	namespace util {

		template < class T, class LockType, typename StorageType = std::deque<T> >
		class LockedQueue
		{
			LockType lock_;
			StorageType queue_;
			/*volatile*/ bool canceled_;

		public:
			LockedQueue()
				: canceled_(false)
			{
			}

			virtual ~LockedQueue()
			{
			}


			void Add(const T& item)
			{
				::node::system::LockGuard<LockType> g(lock_);
				queue_.push_back(item);
			}

			bool Next(T& result)
			{
				::node::system::LockGuard<LockType> g(lock_);
				if (!g.IsLocked()) {
					return false;
				}

				if (queue_.empty()) {
					return false;
				}

				result = queue_.front();
				queue_.pop_front();

				return true;
			}

			template<class Checker>
			bool Next(T& result, Checker& check)
			{
				::node::system::LockGuard<LockType> g(lock_);
				if (!g.IsLocked()) {
					return false;
				}

				if (queue_.empty()) {
					return false;
				}

				result = queue_.front();
				if (!check.Process(result)) {
					return false;
				}

				queue_.pop_front();
				return true;
			}

			T& Peek()
			{
				Lock();
				T& result = queue_.front();
				return result;
			}

			void Cancel()
			{
				::node::system::LockGuard<LockType> g(lock_);
				canceled_ = true;
			}

			bool cancelled()
			{
				::node::system::LockGuard<LockType> g(lock_);
				return canceled_;
			}

			void Lock()
			{
				lock_.Lock();
			}

			void Unlock()
			{
				lock_.Unlock();
			}

			bool Empty()
			{
				::node::system::LockGuard<LockType> g(lock_);
				return queue_.empty();
			}
		};

	}
}

#endif // NODE_UTIL_LOCKED_QUEUE_H_
